//
//  ST_ReceiveThumbUpByEmojiController.swift
//  btvideo
//
//  Created by mac on 2020/4/28.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import SDWebImage
import MJRefresh
import HandyJSON
import SwiftyUserDefaults

class ST_ReceiveThumbUpByEmojiController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        title_nav_btn.setTitleForAllStates("收到点赞")
        
        view.backgroundColor = Color.white
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(own_navigation_bar.snp.bottom)
            make.bottom.right.left.equalToSuperview()
        }
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.currentPage = 0
            self?.request_data()
        })
        
        self.request_data()
        
    }
    
    fileprivate var currentPage = 0
    
    fileprivate func request_data(){
        
        currentPage += 1
        
        let param = ["page":currentPage,
                    "size":20] as [String : Any]

        JVrequest(PH.getReceiveThumbListApi,parameters: param, success: { (json) in

            var count = 0
            
            if let list = [ST_ReceiveThumbUpByEmojiCellModel].deserialize(from: json["data"].rawString() ?? "" ) as? [ST_ReceiveThumbUpByEmojiCellModel]{
                
                list.forEach { (item) in
                    item.createText()
                }
                
                if self.currentPage == 1{
                    self.data_array = list
                }else{
                    self.data_array += list
                }
                count = list.count
            }
            
            self.collectionView.reloadData()
            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
            
            self.collectionView.footer_refresh(count: count) {[weak self] in
                
                self?.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                    self?.request_data()
                })
            }
            
            /*
            if count < 1{
                
                self.collectionView.mj_footer = nil
                
            }else if self.collectionView.mj_footer == nil{
                
                self.collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {[weak self] in

                    self?.request_data()
                })
            }*/

        }) { (code, error) in

            ToastHud(text: error, view: self.view)

            self.collectionView.mj_header?.endRefreshing()
            self.collectionView.mj_footer?.endRefreshing()
        }
    }
    
//    MARK: - Properties
    lazy var itemWidth:CGFloat = {
        return ScreenWidth
    }()
    
//    lazy var itemHeight = 114.cgFloat
    
    lazy var collectionView: UICollectionView = {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = CGSize.init(width: itemWidth, height: ST_ReceiveThumbUpByEmojiCell.height)
        
//        layout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: 65)
        
        layout.minimumLineSpacing = 0
        //        layout.minimumInteritemSpacing = 14
        
        let bottomEdge = iPhoneXSeries ? BTSafeAreaBottom + 30 : 20 + 20
        
//        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 15, bottom: bottomEdge, right: 0)
        
        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        
        collection.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: bottomEdge, right: 0)
        
        collection.register(cellWithClass: ST_ReceiveThumbUpByEmojiCell.self)
        
        collection.delegate = self
        
        collection.dataSource = self
        
        collection.alwaysBounceVertical = true
        
        collection.backgroundColor = Color.white
        
        if #available(iOS 11.0, *) {
            collection.contentInsetAdjustmentBehavior = .never
        }
        return collection
    }()
    
    fileprivate var data_array = [ST_ReceiveThumbUpByEmojiCellModel]()

}

extension ST_ReceiveThumbUpByEmojiController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_ReceiveThumbUpByEmojiCell.self, for: indexPath)
        
        let cellModel = self.data_array[indexPath.item]
        
        cell.model = cellModel
        
        return cell
    }
    
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        

        guard let model = self.data_array[safe:indexPath.row],let fec = model.feature_detail,let myId = ST_BTUserInfoManager.shared.current_account_info?.accid else { return  }
               
        if model.daily_content_id > 0{
            
            let vc = ST_DaliyMomentDetailController()
                    
            vc.dailyId = model.daily_content_id.string
            
            vc.userId = Defaults[.currentUserID]
            
            self.navigationController?.pushViewController(vc)
            return
        }
        
        
        
        let vc = ST_PeculiarityGroupViewController.init(accid: myId, groupId: model.group_id.string, peculiarity_id: fec.feature_id.string, firstPhotoSize: CGSize.init(width: fec.width.cgFloat, height: fec.height.cgFloat), remark: "")
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav, animated: true)
    }
    
    
}


//MARK: - Cell
fileprivate class ST_ReceiveThumbUpByEmojiCell: UICollectionViewCell{
    
    static let height = 108.cgFloat
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    
        contentView.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize.init(width: 46, height: 46))
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(17)
        }
        
        contentView.addSubview(nickname_label)
        nickname_label.snp.makeConstraints { (make) in
            make.left.equalTo(avatar_image_view.snp.right).offset(10)
            make.top.equalTo(avatar_image_view).offset(2)
            make.height.equalTo(22)
            
            if ScreenWidth < 380{
                make.width.lessThanOrEqualTo(100)
            }
        }
        
        contentView.addSubview(time_label)
        time_label.snp.makeConstraints { (make) in
            make.left.equalTo(avatar_image_view.snp.right).offset(10)
            make.top.equalTo(nickname_label.snp.bottom).offset(3)
            make.height.equalTo(17)
        }
        
        contentView.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label)
            make.bottom.equalToSuperview().offset(-15)
            make.height.equalTo(20)
        }
        
        contentView.addSubview(peculiarity_image_view)
        peculiarity_image_view.snp.makeConstraints { (make) in
            make.size.equalTo(CGSize.init(width: 50, height: 50))
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(15)
        }
        
        contentView.addSubview(sign_image_container)
        sign_image_container.snp.makeConstraints { (make) in
            make.left.equalTo(nickname_label.snp.right).offset(4)
            make.centerY.equalTo(nickname_label).offset(-1)
            make.height.equalTo(18)
            make.width.equalTo(70)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var model = ST_ReceiveThumbUpByEmojiCellModel(){
        didSet{
            
            
            
            avatar_image_view.pin_setImage(from: model.avatar.compress_small_image(width: 100).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            if let pecModel = model.feature_detail,pecModel.content.count > 2 {
                
                peculiarity_image_view.pin_setImage(from: pecModel.content.compress_small_image(width: 100).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
                peculiarity_image_view.isHidden = false
            }else{
                peculiarity_image_view.isHidden = true
            }
            
            nickname_label.text = model.nickname
            
            time_label.text = model.timeStr
            
            content_label.text = model.displayContent
            
            
            sign_image_container.bind_data(isVip: CHECK_MEMBER_STATUS(expirationTime: model.vip_expire) == .subscribe, detectedFace: model.face_audit_state == 3)
            
        }
    }
    
//    MARK: Properties

    fileprivate lazy var avatar_image_view:UIImageView = {
         let control = UIImageView()
          control.contentMode = .scaleAspectFill
        control.cornerRadius = 46/2.0
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(push_user_center_handle))
        control.isUserInteractionEnabled = true
        control.addGestureRecognizer(tap)
          return control
      }()
    
    fileprivate lazy var peculiarity_image_view:UIImageView = {
       let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 13
        return control
    }()

    fileprivate lazy var nickname_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#333333")
//        control.numberOfLines = 0
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()

    fileprivate lazy var time_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#ACB4C0")
//        control.numberOfLines = 0
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#61666F")
//        control.numberOfLines = 0
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var sign_image_container:ST_UserSignView = {
        let control = ST_UserSignView()
        return control
    }()
    
    @objc fileprivate func push_user_center_handle(){
        
            
            let vc = ST_PairsCenterViewController()
            
            vc.accid = self.model.accid

            let nav = PairsCenterInteractiveNavigationController.init(rootViewController: vc)
            
            nav.overCurrentContext = true
            
            GlobalPresent(toController: nav)
   
        
        
    }
    
}

//MARK: - Model
fileprivate class ST_ReceiveThumbUpByEmojiCellModel:NSObject,HandyJSON{
    
    var avatar = ""
    
    var accid = ""
    
    var nickname = ""
    
    var create_time = 0
    
    var feature_name = ""
    
    var feature_detail:ST_ReceiveThumbUpByPecModel?
    
    var displayContent = ""
    
    var timeStr = ""
    
    var group_id = 0
    
    var daily_content_id = 0
    
    var vip_expire = 0
    
    var face_audit_state = 0
    
    var type_name = ""
//    var content = Array<ST_PecThumbUpModel>()
    
    required override init() {
        super.init()
    }
    
    
    func createText(){
        
        timeStr = create_time.double.b_t_global_date_string()
        
        let str = "给你的\(type_name) \(feature_name) 点了赞"
        
        displayContent = str
        
    }
}

fileprivate struct ST_ReceiveThumbUpByPecModel:HandyJSON{
    var feature_id = 0
    var content = ""
    var width = 0.0
    var height = 0.0
}


class ST_PecThumbUpModel: NSObject,HandyJSON {
    
    var key = ""
    var value = ""
    
    var num = 0
    
    required override init() {
        super.init()
    }
    
    
}

